﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Configuration;

namespace Mall.Infrastructure.Repository
{
    internal class EFRepositoryContext : IRepositoryContext
    {
        private ObjectContext objContext;
        private Dictionary<Type, object> repositoryCache = new Dictionary<Type, object>();
        public EFRepositoryContext(ObjectContext objContext)
        {
            this.objContext = objContext;
        }


        public EFRepositoryContext(string connection)
        {
            if (ConfigurationManager.ConnectionStrings[connection] == null)
            {
                throw new Exception(string.Format("can not find the {0} connection",connection));
            }
            else
            {
                this.objContext = new ObjectContext(ConfigurationManager.ConnectionStrings[connection].ConnectionString);
            }
        }


        #region IRepositoryTransactionContext Members
        public IRepository<TEntity> GetRepository<TEntity>() where TEntity :class
        {
            if (repositoryCache.ContainsKey(typeof(TEntity)))
            {
                return (IRepository<TEntity>)repositoryCache[typeof(TEntity)];
            }

            IRepository<TEntity> repository = new EdmRepository<TEntity>(this.objContext);
            this.repositoryCache.Add(typeof(TEntity), repository);
            return repository;
        }
        public void BeginTransaction()
        {
            // We do not need to begin a transaction here because the object context,
            // which would handle the transaction, was created and injected into the
            // constructor by Castle Windsor framework.
        }
        public void Commit()
        {
            this.objContext.SaveChanges();
        }
        public void Rollback()
        {
            // We also do not need to perform the rollback operation because
            // entity framework will handle this for us, just when the execution
            // point is stepping out of the using scope.
        }
        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            this.repositoryCache.Clear();
            this.objContext.Dispose();
        }
        #endregion
    }
}
